# seed.py

import json # 如果你的数据定义中需要处理 JSON
from flask import Flask, current_app # <--- 确保导入了 current_app
from app import create_app, db
from app.models import User, Outcome, OutcomeType
# 1. 从你的 app 包导入 create_app 工厂函数和 db 实例
#    假设它们都在 app/__init__.py 中定义或初始化
from app import create_app, db

# 2. 从 app.models 导入你需要填充数据的模型
from app.models import User, OutcomeType # 根据需要添加其他模型，如 Outcome


print(f"[seed.py] Imported db instance. ID: {id(db)}") # 打印导入的 db ID
# --- 在这里定义你的初始数据 ---
# (请确保这里的结构和你模型定义以及 data.js 中的数据一致)
default_users_data = [
    {'username': 'admin', 'password': '123', 'role': 'admin'}, # 密码会在下面被哈希
    {'username': 'user1', 'password': '123', 'role': 'normal'},
    {'username': 'user2', 'password': '123', 'role': 'normal'},
]

default_outcome_types_data = [
    {
        "id": 'paper',
        "name": '论文',
        "config_data": { # 确保这个键名 ('config_data') 和你模型中的字段名一致
            "requiredFields": ["title", "authors", "journalConference", "publishDate", "projectSupport"],
            "optionalFields": ["doi", "issn", "journalPartition", "inclusionStatus", "impactFactor"],
            "authorship": True,
            "fieldLabels": {
                "title": "标题", "authors": "作者列表", "journalConference": "发表期刊/会议 (等级)",
                "publishDate": "发表时间", "projectSupport": "项目支撑", "doi": "DOI", "issn": "ISSN",
                "journalPartition": "期刊分区", "inclusionStatus": "收录情况", "impactFactor": "影响因子"
            },
            "fieldPlaceholders": {
                "title": "论文标题", "journalConference": "如：Nature, SCI一区",
                "publishDate": "YYYY-MM-DD", "doi": "如：10.1038/s41586-023-06670-3"
            },
            "fieldTypes": {"publishDate": "date"},
            "attachments": True
        }
    },
    {
        "id": 'patent',
        "name": '专利',
        "config_data": { # 确保这个键名和你模型中的字段名一致
            "requiredFields": ["title", "inventorsDesigners", "patentNumber"],
            "optionalFields": ["patentType", "applicationDate", "authorizationDate", "affiliation"],
            "authorship": True,
            "fieldLabels": {
                "title": "专利标题", "inventorsDesigners": "发明人/设计人列表", "patentNumber": "专利号",
                "patentType": "专利类型", "applicationDate": "申请日期", "authorizationDate": "授权日期",
                "affiliation": "成果所属部门/学院"
            },
            "fieldPlaceholders": {
                "title": "专利标题", "patentNumber": "如：CN123456789U",
                "applicationDate": "YYYY-MM-DD", "authorizationDate": "YYYY-MM-DD", "affiliation": "如：计算机学院"
            },
            "fieldTypes": {"applicationDate": "date", "authorizationDate": "date"},
            "dropdownOptions": {"patentType": ["发明专利", "实用新型", "外观设计"]},
            "attachments": True
        }
    },
     {
        "id": 'competition',
        "name": '竞赛',
        "config_data": { # 确保这个键名和你模型中的字段名一致
            "requiredFields": ["competitionName", "competitionLevel", "awardLevel", "competitionType"],
            "optionalFields": ["participants", "myRank", "awardDate"],
            # "authorship": false, # data.js 中可能笔误，这里移除了，以模型为准
            "fieldLabels": {
                "competitionName": "竞赛名称", "competitionLevel": "竞赛等级", "awardLevel": "获奖等级",
                "competitionType": "竞赛类型", "participants": "参赛队员", "myRank": "本人在参赛成员中的排名",
                "awardDate": "获奖日期"
            },
            "fieldPlaceholders": {"competitionName": "如：全国大学生程序设计竞赛", "awardDate": "YYYY-MM-DD"},
            "fieldTypes": {"awardDate": "date"},
            "dropdownOptions": {"competitionLevel": ["国家级", "省部级", "市厅级", "校级", "国际级"], "competitionType": ["个人竞赛", "团队竞赛"]},
            "attachments": True
        }
    },
    {
        "id": 'researchProject',
        "name": '科研项目',
        "config_data": { # 确保这个键名和你模型中的字段名一致
            "requiredFields": ["projectName", "projectLeader", "participantsRanked", "projectLevel"],
            "optionalFields": ["projectStatus", "affiliation"],
            "authorship": True,
            "fieldLabels": {
                "projectName": "项目名称", "projectLeader": "项目负责人", "participantsRanked": "参与成员及其排名",
                "projectLevel": "项目级别", "projectStatus": "项目状态", "affiliation": "成果所属部门/学院"
            },
            "fieldPlaceholders": {
                "projectName": "如：国家自然科学基金项目", "projectLeader": "项目负责人姓名", "affiliation": "如：计算机学院"
            },
            "dropdownOptions": {"projectLevel": ["国家级", "省部级", "市厅级", "校级"], "projectStatus": ["在研", "已结题", "中期检查通过", "延期", "终止"]},
            "attachments": True
        }
    }
]


# --- 定义数据填充函数 ---
def seed_database():
    print("Seeding database...")
    try:
        # --- Seed Users ---
        print("Seeding users...")
        for user_data in default_users_data:
            # 检查用户是否已存在
            user = User.query.filter_by(username=user_data['username']).first()
            if not user:
                # 创建新用户实例
                new_user = User(username=user_data['username'], role=user_data['role'])
                # 设置密码 (假设 User 模型有 set_password 方法来处理哈希)
                new_user.set_password(user_data['password'])
                # 添加到 session
                db.session.add(new_user)
                print(f"Added user: {user_data['username']}")
            else:
                print(f"User already exists: {user_data['username']}")

        # --- Seed Outcome Types ---
        print("\nSeeding outcome types...")
        for type_data in default_outcome_types_data:
            # 检查成果类型是否已存在 (通过 ID)
            otype = OutcomeType.query.get(type_data['id'])
            if not otype:
                # 创建新成果类型实例
                # 确保 config_data 存在且是字典
                config_data = type_data.get('config_data', {}) # 使用 .get 提供默认空字典
                if not isinstance(config_data, dict):
                   print(f"Warning: Config data for {type_data['id']} is not a dictionary. Skipping.")
                   continue

                new_type = OutcomeType(
                    id=type_data['id'],
                    name=type_data['name'],
                    config_data=config_data # 直接传递 Python 字典
                )
                # 添加到 session
                db.session.add(new_type)
                print(f"Added outcome type: {type_data['name']}")
            else:
                print(f"Outcome type already exists: {type_data['id']}")

        # --- 提交所有更改 ---
        db.session.commit()
        print("\nDatabase seeding completed successfully!")

    except Exception as e:
        # 如果出错，回滚事务
        db.session.rollback()
        print(f"\nError seeding database: {e}")
        # 可以选择重新抛出异常，以便看到更详细的堆栈跟踪
        # raise
    # finally:
        # 在应用上下文中，session 通常会自动处理，一般不需要显式 close
        # db.session.close()


# --- 脚本执行入口 ---
if __name__ == '__main__':
    print("[seed.py] Main block started.")
    app = create_app()
    print(f"[seed.py] App created. Using db instance with ID: {id(db)}") # 再次确认 db ID

    with app.app_context():
        print(f"[seed.py] Inside app_context. Using db instance with ID: {id(db)}") # 上下文内的 db ID
        # 确认上下文内的 db 是否有关联的 app
        # seed.py, line 171 (修改后)
        current_db_app_in_context = current_app  # <--- 使用 current_app
        print(f"[seed.py] Inside app_context. Current app ID: {id(current_db_app_in_context)}")  # 可以加个日志确认

        seed_database()
    print("[seed.py] Script finished.")

